<template>
	<view class="upload-box mb-3">
		<view class="cu-form-group">
			<view class="grid col-5 grid-square flex-sub">
				<view class="bg-img" v-for="(item, index) in fileList" :key="index" @tap="viewFile(item)" :data-url="fileList[index]">
					<image :src="calcIcon(item)" mode="aspectFill" />
					<view class="file-name text-ellipsis-1">{{ item.filename }}</view>
					<view v-if="!disabled" class="cu-tag bg-red" @tap.stop="delFile" :data-index="index">
						<text class='cuIcon-close'></text>
					</view>
				</view>
				<view class="solids" @tap="handleShow" v-if="fileList.length < 9">
					<text class='cuIcon-add'></text>
				</view>
			</view>
		</view>
	</view>
	<Modal ref="modal">
		<view class="padding-xl">
			<view class="flex justify-around">
				<view class="text-black" @click="chooseImage('camera')">
					<view class="icon text-blue"><text class="cuIcon-camerafill"></text></view>
					<view class="icon-text">拍照</view>
				</view>
				<view class="text-black" @click="chooseImage('album')">
					<view class="icon text-blue"><text class="cuIcon-picfill"></text></view>
					<view class="icon-text">上传图片</view>
				</view>
				<view class="text-black" @click="handleChooseFile">
					<view class="icon text-blue"><text class="cuIcon-squarecheckfill"></text></view>
					<view class="icon-text">上传文件</view>
				</view>
			</view>
		</view>
	</Modal>
</template>

<script setup lang="ts">
import { Ref, ref, onMounted } from "vue"
import { router } from "@/router"
import env from "@/env"
import { uploadFile } from "@/api/common.js"
import path from "path-browserify"
import { downloadFile } from "@/utils/common"
import Modal from "./Modal.vue"
import store from "@/store/index.js"
// #ifdef H5
import dd from "gdt-jsapi"
// #endif

interface IFile {
	localPath: string
	serverPath: string
	suffix: string
	filename: string
}
const props = defineProps({
	fieldFiles: {
		type: Array,
		default: []
	},
	disabled: {
		type: Boolean,
		default: false
	}
})
const emit = defineEmits(["update:fieldFiles", "change"])

const modal = ref()
const fileList: Ref<any[]> = ref([] as any[])
const viewFile = (file: any):void => {
	// #ifdef H5
	if (file.suffix === "docx") {
		if (store.getters.osName === "ios") {
			router.push("/pages/index/word?title=" + file.filename + "&filepath=" + file.serverPath)
		} else {
			location.href = file.filename
		}
	}
	if (file.suffix === "png" || file.suffix === 'jpeg' || file.suffix === 'jpg') {
		uni.previewImage({
			urls: [file.serverPath],
			current: file.serverPath
		})
	}
	// #endif
}

const calcIcon = (item: IFile):string => {
	if (item.suffix === 'docx') {
		return env.H5_RELATIVE_URL + '/static/images/docx_icon.png'
	} else if (item.suffix === 'png' || item.suffix === 'jpg' || item.suffix === 'jpeg') {
		return item.serverPath
	} else {
		return env.H5_RELATIVE_URL + '/static/images/otherfile_icon.png'
	}
}

/**
 * 删除文件
 */
const delFile= (e:any):void => {
	uni.showModal({
		title: '删除',
		content: '确定要删除这个文件？',
		cancelText: '取消',
		confirmText: '确认',
		success: res => {
			if (res.confirm) {
				fileList.value.splice(e.currentTarget.dataset.index, 1)
				emit("update:fieldFiles", fileList.value)
				emit("change")
			}
		}
	})
}

const chooseImage = (sourceType = ''):void => {
	modal.value.hide()
	
	
	if (sourceType === "album") {
		dd.chooseImage({})
			.then(async (res: any) => {
				uni.showLoading({
					title: "上传中"
				})
				try {
					for (let item of res.images) {
						const file = await uploadProcess(item.path)
						if (file.code === 200) {
							fileList.value.push({
								localPath: "",
								serverPath: file.url,
								suffix: file.originalFilename.match(/\.[^.]+$/g)[0].substring(1),
								filename: file.originalFilename,
							})
							emit("update:fieldFiles", fileList.value)
							emit("change")
						}
					}
					uni.hideLoading()
				} catch (err) {
					uni.hideLoading()
				}
			})
			.catch((err: any) => {
				console.log(err)
				// uni.showToast({
				// 	icon: "none",
				// 	title: JSON.stringify(err)
				// })
			})
	} else {
		dd.takePhoto().then(async (res: any) => {
			// uni.showToast({
			// 	icon: "none",
			// 	title: JSON.stringify(res)
			// })
			uni.showLoading({
				title: "上传中"
			})
			try {
				const file = await uploadProcess(res.path)
				if (file.code === 200) {
					fileList.value.push({
						localPath: "",
						serverPath: file.url,
						suffix: file.originalFilename.match(/\.[^.]+$/g)[0].substring(1),
						filename: file.originalFilename,
					})
					emit("update:fieldFiles", fileList.value)
					emit("change")
				}
				uni.hideLoading()
			} catch (err) {
				uni.hideLoading()
			}
		}).catch(async (err: any) => {
			// uni.showToast({
			// 	icon: "none",
			// 	title: JSON.stringify(err)
			// })
		})
	}
	
	
	// uni.chooseImage({
	// 	count: 9, //默认9
	// 	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
	// 	sourceType: ['album', 'camera'], //从相册选择
	// 	success: async (res) => {
	// 		// const imgTempList = []
	// 		console.log(res)
	// 		if (typeof res.tempFilePaths === "object") {
	// 			// imgList.value = res.tempFilePaths
	// 			for (let v of res.tempFilePaths) {
	// 				try {
	// 					const res = await uploadFile({
	// 						filePath: v,
	// 						name: "file",
	// 					})
	// 					fileList.value.push({
	// 						localPath: "",
	// 						serverPath: res.url,
	// 						suffix: res.originalFilename.match(/\.[^.]+$/g)[0].substring(1),
	// 						filename: res.originalFilename,
	// 					})
	// 					emit("update:fieldFiles", fileList.value)
	// 				} catch (err) {
	// 					console.log(err)
	// 					router.push("/pages/index/server_error")
	// 				}
	// 			}
	// 		}
	// 	},
	// 	fail: (err) => {
	// 		modal.value.hide()
	// 	}
	// })
}

const handleShow = (): void => {
	if (!props.disabled) {
		modal.value.show()
	}
	
}

/**
 * 上传文件
 */
const handleChooseFile = (): void => {
	modal.value.hide()
	dd.chooseFile({
		// "maxNum": 3
		multiSelection: true
	}).then(async (res) => {
		uni.showLoading({
			title: "上传中"
		})
		try {
			for (let file of res.files) {
				const result = await uploadProcess(file.path)
				if (result.code === 200) {
					fileList.value.push({
						localPath: file.path,
						serverPath: result.url,
						suffix: result.originalFilename.match(/\.[^.]+$/g)[0].substring(1),
						filename: result.originalFilename,
					})
					emit("update:fieldFiles", fileList.value)
					emit("change")
				}
			}
			uni.hideLoading()
		} catch (err) {
			uni.hideLoading()
		}
	}).catch((err) => {
		console.log(err)
	})
}

/**
 * 处理上传的文件
 */
const uploadProcess = async (filePath:string = ""): Promise<any> => {
	let res = null
	// #ifdef MP-ALIPAY
	res = await uploadFile({
		filePath,
		name: path.basename(filePath)
	})
	// #endif
	// #ifdef H5
	try {
		// res = await dd.uploadFile({
		// 	filePath: [ filePath ]
		// })
		// const result = await downloadFile({
		// 	media_id: res[0],
		// 	ext: filePath.match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[1]
		// })
		// res = {
		// 	code: 200,
		// 	url: result.filepath,
		// 	originalFilename: path.basename(filePath)
		// }
		const uploadRes = await dd.uploadFile({
			filePath: [ filePath ]
		})
		const result = await downloadFile({
			media_id: uploadRes[0],
			ext: filePath.match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[1]
		})
		res = {
			code: 200,
			url: result.filepath,
			originalFilename: path.basename(filePath)
		}
		return res
		
		// if (res.code === 200) {
		// 	fileList.value.push({
		// 		localPath: filePath,
		// 		serverPath: res.url,
		// 		suffix: res.originalFilename.match(/\.[^.]+$/g)[0].substring(1),
		// 		filename: res.originalFilename,
		// 	})
		// 	emit("update:fieldFiles", fileList.value)
		// }
	} catch (err) {
		router.push("/pages/index/server_error")
	}
	
	
	// #endif
}
onMounted(() => {
	fileList.value = props.fieldFiles
})

</script>

<style lang="stylus" scoped>
// .upload-box
	
.cu-form-group
	padding 0
.file-name
	position: absolute
	bottom: 0
	height: 30%
	text-align: center
	width: 100%
	color: #626262
	font-size 24rpx
	
.grid.grid-square>uni-view.bg-img uni-image
	height: 70%
	width: 70%;
	margin: 0 15%
	
.icon
	font-size: 72rpx
.icon-text
	font-size: 24rpx
</style>